import request from '@/utils/request'
import {envConfig} from '@/config'
import {IResponseType, PostDataType} from './interface'
import CryptoJS from 'crypto-js';
import auth from "@/utils/auth";

export const fetchPost = (data: object, method: string) => {
    data = setData(data, method)
    return request<IResponseType>({
        url: envConfig.baseApi,
        method: 'post',
        data,
        loading: true
    })
}
const setData = (data: object, method: string) => {
    const param_json = {};
    let isFormData = false;
    const app_key = envConfig.appKey;
    const token = auth.getToken() ?? '';
    //组装参数
    const params = {
        app_key: app_key,
        app_version: envConfig.version,
        method: method,
        timestamp: Date.now(),
        timeout: 120,
        noncestr: roundStr(),
        token: token,
        param_json: '',
        sign: ''
    }
    if (data instanceof FormData) {
        isFormData = true;
        data.forEach((value, key) => {
            param_json[key] = value
            if (value instanceof File) {
                params[key] = value
            } else {
                param_json[key] = value
            }
        });
    } else {
        for (const key in data) {
            const value = data[key]
            if (typeof value === 'function') continue;
            param_json[key] = value
        }
    }
    params.param_json = JSON.stringify(param_json)
    //仅以下参数参与签名
    let sortStr = sortParams({
        method: params.method,
        token: params.token,
        app_key: params.app_key,
        timeout: params.timeout,
        app_version: params.app_version,
        timestamp: params.timestamp,
        noncestr: params.noncestr,
        param_json: params.param_json
    })
    sortStr = envConfig.appSecret + sortStr + envConfig.appSecret
    params.sign = CryptoJS.MD5(sortStr).toString().toUpperCase()
    if (!isFormData) {
        return <PostDataType><unknown>params;
    } else {
        const formData = new FormData();
        for (const key in params) {
            formData.append(key, params[key]);
        }
        return <PostDataType><unknown>formData;
    }
}
const roundStr = () => {
    let str = ''
    const arr = [
        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
        'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
        'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'
    ];
    for (let i = 0; i < 32; i++) {
        const id = (Math.random() * 61).toString()
        str += arr[parseInt(id)]
    }
    return str
}
const sortParams = (params) => {
    let str = ''
    const newKey = Object.keys(params).sort()
    for (const value of newKey) {
        str += value + params[value]
    }
    return str
}
